package com.taobao.open.servlet;

import java.io.IOException;
import java.io.Writer;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.taobao.tql.TQLQuery;

/**
 * Servlet implementation class TqlSendServlet
 */
public class TqlSendServlet extends HttpServlet {

	/**
	 * serialVersionUID:TODO（用一句话描述这个变量表示什么）
	 * 
	 * @since 1.0.0
	 */

	private static final long serialVersionUID = 6905947466519470224L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doPost(request, response);
	}

	/**
	 * The doPost method of the servlet. <br>
	 * 
	 * This method is called when a form has its tag value method equals to
	 * post.
	 * 
	 * @param request
	 *            the request send by the client to the server
	 * @param response
	 *            the response send by the server to the client
	 * @throws ServletException
	 *             if an error occurred
	 * @throws IOException
	 *             if an error occurred
	 */
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		/**
		 * 设置Ajax响应头信息
		 */
		response.setContentType("text/html,charset=UTF-8");
		response.setCharacterEncoding("UTF-8");
		response.setHeader("Cache-Control", "no-store");
		response.setHeader("Pragma", "no-cache");
		response.setDateHeader("Expires", 0);
		Writer writer = null;
		
		String strSql = request.getParameter("sql");

		if (strSql == null) {
			/**
			 * 你的错误处理
			 */
			throw new RuntimeException();
		} else {
			// 解析数据
			TQLQuery tqlQuery = new TQLQuery(strSql, null);
			String strRtn = tqlQuery.TQLQueryExcu();
			/**
			 * 拿到返回结果
			 */
			// String result =
			// Util.getResult(Config.SANDBOX_URL,param.toString().substring(1));
			/**
			 * 这里不拿xml解析引擎解析了，只是简单的判断是否成功
			 */
			// if(result.matches(".*<shipping><is_success>true</is_success></shipping>.*")){
			if (strRtn != null) {
				if(strRtn.indexOf("<?xml") < 0) {
					strRtn = tqlQuery.getXmlFromStr(strRtn);
				}
				try {
					writer = response.getWriter();
					writer.write(strRtn);
				} finally {
					/**
					 * 记得关闭
					 */
					if (writer != null) {
						writer.close();
					}
				}

			} else {
				/**
				 * 你的错误处理
				 */
				throw new RuntimeException();
			}
		}
	}

}
